package com.dfrz.problem.action.login;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dfrz.problem.model.Employee;
import com.dfrz.problem.model.ProjectInfo;
import com.dfrz.problem.model.SysAdmin;
import com.dfrz.problem.model.User;
import com.dfrz.problem.service.LoginService;
import com.dfrz.problem.service.ProjectService;
import com.dfrz.problem.utils.IConstant;
import com.dfrz.problem.utils.Result;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);

	private User user;
	private LoginService loginService;
	private ProjectService projectService;
	private Employee employee;
	private ProjectInfo projectInfo;
	private int rememberPwd;// 是否记住密码

	/**
	 * 系统登录方法
	 * @return
	 */
	public String login() {
		String u = getCookie("user.email");
		logger.debug("user:{}",u);
		user.setEmail(getCookie("user.email"));
		user.setPassword(getCookie("user.password"));
		return SUCCESS;
	}
	
	/**
	 * 进入系统主页
	 * @return
	 */
	public String index(){
		SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext
				.getContext().getSession();
		user = (User) session.get("user");
		if(user.getLoginType() == 1){
			employee = (Employee) session.get("employee");
			projectInfo = projectService.getProjectOnId(employee.getProject().getProjectId()).getResult();			
		}
		
		return SUCCESS;
	}

	/**
	 * 退出登录
	 * @return
	 */
	public String logout() {
		SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext
				.getContext().getSession();
		// 除出当前会话中所有的保存的对象
		session.clear();
		// 将当前会话失效
		session.invalidate();
		
		return SUCCESS;
	}

	/**
	 * 登录前的信息校验
	 */
	public void validateCheckLogin() {
		if (user == null) {
			addActionError(getText(IConstant.ERR_CODE_NEED_USER_PASSWORD));
			return;
		}
		if (StringUtils.isEmpty(user.getEmail())) {
			// 不使用国际化
			addFieldError("user.email", "用户帐号不能为空.");
		}
		if (StringUtils.isEmpty(user.getPassword())) {
			addFieldError("user.password", "用户密码不能空.");
		}
	}

	/**
	 * 登录信息校验
	 * @return
	 */
	public String checkLogin() {
		Result<Object> result = loginService.checkLogin(user);
		SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext
				.getContext().getSession();

		// 验证是否登录成功
		if (IConstant.LOGIN_SUCCESS.equals(result.getCode())) {
			ActionContext.getContext().getSession()
					.put(IConstant.KEY_SES_LOGIN_USER, result.getResult());
			
			logger.debug("uesr: " + user.getEmail() + " is login...");
			
			// 记住密码
			if(rememberPwd == 1){
				addCookie(user.getEmail(),user.getPassword());
			}
			
			addActionMessage(user.getUserName());
			
			// 判断登录用户的角色
			if(result.getResult() instanceof SysAdmin){
				session.put("sysAdmin", (SysAdmin)result.getResult());
				user.setRole("系统管理员");
			}else{
				employee = (Employee)result.getResult();
				session.put("employee", employee);
				user.setRole(employee.getRole()==null? "未分配":employee.getRole().getRoleName());
			}
			session.put("user", user);
			index();
			return SUCCESS;
		} else {
			addActionError(getText(result.getCode()));
			return LOGIN;
		}

	}
	
	/**
	 * 设置Cookie保存用户登录信息
	 * @param userName
	 * @param pwd
	 */
	public void addCookie(String userName,String pwd){
		logger.debug("add Cookie ...");
		Cookie email = new Cookie("user.email", userName);
		Cookie password = new Cookie("user.password",pwd);
		// cookie存活时间为1天
		email.setMaxAge(60*60*24);
		password.setMaxAge(60*60*24);
		ServletActionContext.getResponse().addCookie(email);
		ServletActionContext.getResponse().addCookie(password);
	}
	
	public String getCookie(String name){
		HttpServletRequest request = ServletActionContext.getRequest();
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies)
        {
            if(cookie.getName().equals(name))
            {
                return cookie.getValue();
            }
        }
		return null;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getUser() {
		return user;
	}
	
	public void setRememberPwd(int rememberPwd) {
		this.rememberPwd = rememberPwd;
	}
	
	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}
	
	public ProjectInfo getProjectInfo() {
		return projectInfo;
	}
}
